import type { FormSchema, ProFormColumnsType } from '@ant-design/pro-form/es/components/SchemaForm'
import { Form } from 'antd'
import { useEffect, useState } from 'react'
export interface FormColumnsGenerater {
    (val?: any): ProFormColumnsType[] | Promise<ProFormColumnsType[]> | Promise<any[]>
}
export const useForm = <T>(_columns: ProFormColumnsType[] | FormColumnsGenerater, onFinish: (values: any) => Promise<boolean | void>) => {
    const [columns, setColumns] = useState<ProFormColumnsType[]>([])
    useEffect(() => {
        if (!open) return;
        if (typeof _columns === 'function') {
            const columns = _columns()
            if (Array.isArray(columns)) {
                setColumns(columns)
            } else {
                columns.then(c => setColumns(c))
            }
        } else {
            setColumns(_columns)
        }
    }, [open])
    const [form] = Form.useForm()
    const props: FormSchema<T> = {
        columns: columns,
        form: form,
        onFinish: async (formData: T) => {
            return onFinish(formData)
        },
    }
    return {
        props,
        form,
        setColumns
    }
}